import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
// 修正 UserService 的导入路径
import { UserService } from '../../user/services/user.service';
// 修正 User 实体的导入路径
import { User } from '../../user/entities/user.entity';

export interface JwtPayload {
  sub: string;
  username: string;
}

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  private readonly logger = new Logger(JwtStrategy.name);

  constructor(
    private readonly userService: UserService,
    private readonly configService: ConfigService,
  ) {
    const jwtSecret = configService.get('jwt.secret');

    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtSecret || 'your-super-secret-jwt-key',
    });

    this.logger.debug(`JWT Secret: ${jwtSecret ? '已配置' : '未配置'}`);
  }

  async validate(payload: any): Promise<User> {
    this.logger.debug('=== JwtStrategy.validate 开始 ===');
    this.logger.debug(`Payload: ${JSON.stringify(payload)}`);

    try {
      // 从数据库获取用户信息
      const user = await this.userService.findByUsername(payload.username);
      this.logger.debug(`Found user: ${user ? '存在' : 'null'}`);

      if (!user) {
        this.logger.warn(`User not found for username: ${payload.username}`);
        this.logger.debug('=== JwtStrategy.validate 结束 (用户不存在) ===');
        throw new UnauthorizedException('用户不存在');
      }

      // 确保返回的用户对象包含必要的字段，避免TypeORM实体序列化问题
      // 使用 Object.assign 来替代手动逐个赋值，这样当 User 实体变化时更容易维护
      const userResult = Object.assign({}, user);

      this.logger.debug(
        `Returning user result: ID=${userResult.id}, Username=${userResult.username}`,
      );
      this.logger.debug('=== JwtStrategy.validate 结束 (成功) ===');
      return userResult as User;
    } catch (error) {
      this.logger.error(`Error validating user: ${error.message}`, error.stack);
      this.logger.debug('=== JwtStrategy.validate 结束 (错误) ===');
      throw new UnauthorizedException('用户验证失败');
    }
  }
}